package com.doform.android.xianggucheng.activity.money;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.doform.android.xianggucheng.BaseTimePickerActivity;
import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.bean.BillBean1;
import com.doform.android.xianggucheng.bean.BillBean2;
import com.doform.android.xianggucheng.bean.request_bean.ReqBill;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.widget.DividerItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

/**
 * 作者 Y_MS
 * Created by ${APEN} on 2017-07-22.
 * GitHub：https://github.com/cxydxpx
 */

public class BillActivity extends BaseTimePickerActivity implements OnRefreshListener, OnLoadmoreListener {

    public static final int PAGE_CONTENT_INIT = 1;
    private int mCurrentPage = PAGE_CONTENT_INIT;

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.tv_query_start)
    TextView mQueryStart;

    @BindView(R.id.tv_query_stop)
    TextView mQueryStop;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private CommonAdapter mCommonAdapter;
    List<BillBean2> mDatas = new ArrayList<>();
    private String sdate;
    private String edate;
    private String isHasPage;

    @Override
    protected int layoutResId() {
        return R.layout.activity_bill;
    }

    @Override
    protected void initView() {
        super.initView();

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        long curTime = System.currentTimeMillis();
        long startTime = curTime - 7 * 24 * 60 * 60 * 1000;

        sdate = formatter.format(new Date(startTime));
        edate = formatter.format(new Date(curTime));

        mQueryStart.setText(sdate);
        mQueryStop.setText(edate);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

    }

    @Override
    protected void showView() {
        titleBar.setBackgroundColor(new ColorDrawable(getResources().getColor(R.color.blue2)));
        titleBar.setTextTitle("账单");
    }

    @Override
    protected void updateData() {
        super.updateData();
        refresh();
    }

    private void refresh() {
        String sdate = mQueryStart.getText().toString().trim();
        String edate = mQueryStop.getText().toString().trim();
        mCurrentPage = PAGE_CONTENT_INIT;
        getDataForService(sdate, edate, mCurrentPage);
    }


    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refresh();
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        if (TextUtils.isEmpty(isHasPage) && isHasPage.equals("true")) {//还有下一页
            mCurrentPage++;
            getDataForService(mQueryStart.getText().toString().trim(),
                    mQueryStop.getText().toString().trim(), mCurrentPage);
        } else {// 不加载
            refreshLayout.finishLoadmore();
        }
    }


    private void getDataForService(String sDate, String eDate, int mCurrentPage) {
        HttpManager
                .instance()
                .getBIllData(new ReqBill(sDate, eDate, String.valueOf(mCurrentPage)))
                .flatMap(new Function<BillBean1, ObservableSource<List<BillBean2>>>() {

                             @Override
                             public ObservableSource<List<BillBean2>> apply(@NonNull BillBean1 billBean1) throws Exception {
                                 isHasPage = billBean1.getHasnextpage();
                                 return Observable.just(JSON.parseArray(billBean1.getTranshisllist(), BillBean2.class));
                             }
                         }
                )
                .subscribe(new ErrorHandleSubscriber<List<BillBean2>>() {
                               @Override
                               public void onNext(@NonNull List<BillBean2> billBean2s) {
                                   parseData(billBean2s);
                               }
                           }
                );
    }

    private void parseData(@NonNull List<BillBean2> list) {

        if (mCurrentPage == PAGE_CONTENT_INIT) {
            mDatas.clear();
        }

        if (mCurrentPage > 1 && (list.size() == 0 || list == null)) {
            mCurrentPage--;
            refreshLayout.finishLoadmore();
            return;
        }

        mDatas.addAll(list);
        mCommonAdapter.notifyDataSetChanged();
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
    }

    @Override
    protected void initListener() {
        super.initListener();
        initRecyclerAdapter();
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadmoreListener(this);
        refreshLayout.setEnableHeaderTranslationContent(false);

    }


    private void initRecyclerAdapter() {

        mCommonAdapter = new CommonAdapter<BillBean2>(this, R.layout.activity_bill_item, mDatas) {
            @Override
            protected void convert(ViewHolder holder, BillBean2 dataBean, int position) {
                TextView tv_date = holder.getView(R.id.tv_date);
                TextView tv_time = holder.getView(R.id.tv_time);
                TextView tv_money = holder.getView(R.id.tv_money);
                TextView tv_detail = holder.getView(R.id.tv_detail);

                tv_date.setText(dataBean.getDate());
//                tv_time.setText(dataBean.getDate());
                tv_money.setText("￥" + dataBean.getAmount());
                tv_detail.setText(dataBean.getMemo());

            }
        };


        mCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Intent intent = new Intent(BillActivity.this, BillDetailActivity.class);
                intent.putExtra(Constans.EXTRA__BILL, mDatas.get(position));
                startActivity(intent);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mRecyclerView.setAdapter(mCommonAdapter);

    }

    @OnClick({R.id.btn_query, R.id.tv_query_start, R.id.tv_query_stop})
    protected void processClick(View v) {
        switch (v.getId()) {
            case R.id.btn_query:
                refresh();
                break;
            case R.id.tv_query_start:
                pvTime.show(mQueryStart);
                break;
            case R.id.tv_query_stop:
                pvTime2.show(mQueryStop);
                break;
            default:
                break;

        }
    }


}
